package com.mt.mall.service.good.impl;

import com.mt.mall.dao.good.EvaluationDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.mall.entity.good.Evaluation;
import com.mt.mall.service.good.EvaluationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class EvaluationServiceBean extends BaseService implements EvaluationService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private EvaluationDao evaluationDao;

	@Resource
	private RedisTemplate<String, List<Evaluation>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询商品评价集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findEvaluations(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindEvaluations(pageDTO);
		List<Evaluation> evaluationDTOS = this.evaluationDao.findEvaluations(pageDTO);
		Long totalCount = this.evaluationDao.findEvaluationTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(evaluationDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部商品评价集合
	 *
	 */
	@Override
	public List<Evaluation> findAllEvaluations(){
		return this.evaluationDao.findAllEvaluations();
	}

	/**
	 * 查询所有商品评价集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<Evaluation> findAllEvaluationsWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllEvaluationsWithIdName();
		return this.evaluationDao.findAllEvaluationsWithIdName();
	}

	/**
	 * 根据名称查询商品评价集合(只提取ID 和 Name)
	 *
	 * @param evaluationName 名称
	 */
	@Override
	public List<Evaluation> findEvaluationsWithIdNameByName(String evaluationName){
		//TODO:请在此校验参数的合法性
		this.validateFindEvaluationsWithIdNameByName(evaluationName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:Evaluation_where_evaluationName_" + evaluationName);
		List<Evaluation> evaluations = new ArrayList<>();
		if (keys.isEmpty()) {
		evaluations = this.evaluationDao.findEvaluationsWithIdNameByName(evaluationName);
		redisTemplate.opsForValue().set("searchData:Evaluation_where_evaluationName_" + evaluationName, evaluations, 30, TimeUnit.DAYS);
		} else {
		evaluations = redisTemplate.opsForValue().get("searchData:Evaluation_where_evaluationName_" + evaluationName);
		}
		return evaluations;
	}

	/**
	 * 根据ID查询指定的商品评价(只提取ID 和 Name)
	 *
	 * @param evaluationId Id
	 */
	@Override
	public Evaluation findEvaluationsWithIdNameById(Long evaluationId){
		//TODO:请在此校验参数的合法性
		this.validateFindEvaluationsWithIdNameById(evaluationId);
		return this.evaluationDao.findEvaluationsWithIdNameById(evaluationId);
	}

	/**
	 * 根据ID查询指定的商品评价
	 *
	 * @param evaluationId Id
	 */
	@Override
	public Evaluation findEvaluation(Long evaluationId){
		//TODO:请在此校验参数的合法性
		this.validateFindEvaluation(evaluationId);
		return this.evaluationDao.findEvaluation(evaluationId);
	}

	/**
	 * 根据ID查询指定的商品评价(包含外键)
	 *
	 * @param evaluationId Id
	 */
	@Override
	public Evaluation findEvaluationWithForeignName(Long evaluationId){
		//TODO:请在此校验参数的合法性
		this.validateFindEvaluationWithForeignName(evaluationId);
		return this.evaluationDao.findEvaluationWithForeignName(evaluationId);
	}

	/**
	 * 新增商品评价
	 *
	 * @param evaluation 实体对象
	 */
	@Override
	public Evaluation saveEvaluation(Evaluation evaluation){
		//TODO:请在此校验参数的合法性
		this.validateSaveEvaluation(evaluation);
		//TODO:填充公共参数
		this.setSavePulicColumns(evaluation);
		Long rows = this.evaluationDao.saveEvaluation(evaluation);
		if(rows != 1)
		{
			String error = "新增保存商品评价出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		return evaluation;
	}

	/**
	 * 更新商品评价
	 *
	 * @param evaluation 实体对象
	 */
	@Override
	public Evaluation updateEvaluation(Evaluation evaluation){
		//TODO:请在此校验参数的合法性
		this.validateUpdateEvaluation(evaluation);
		Long rows = this.evaluationDao.updateEvaluation(evaluation);
		if(rows != 1)
		{
			String error = "修改保存商品评价出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return evaluation;
	}

	/**
	 * 根据ID删除商品评价
	 *
	 * @param evaluationId ID
	 */
	@Override
	public void deleteEvaluation(Long evaluationId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteEvaluation(evaluationId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(Evaluation.class, evaluationId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.evaluationDao.deleteEvaluation(evaluationId);
		if(rows != 1){
			String error = "删除商品评价出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	//TODO:---------------验证-------------------

	private void validateFindEvaluations(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateEvaluation()写法
	}

	private void validateFindEvaluationsWithIdNameByName(String evaluationName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateEvaluation()写法
	}


	private void validateFindAllEvaluationsWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateEvaluation()写法
	}

	private void validateFindEvaluationsWithIdNameById(Long evaluationId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateEvaluation()写法
	}

	private void validateFindEvaluation(Long evaluationId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateEvaluation()写法
	}

	private void validateFindEvaluationWithForeignName(Long evaluationId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateEvaluation()写法
	}

	private void validateSaveEvaluation(Evaluation evaluation) {
	//不为空判断
	if (evaluation.getEid() != null || evaluation.getCreatorId() != null || evaluation.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateEvaluation()写法
	}

	private void validateUpdateEvaluation(Evaluation evaluation) {
	//不为空判断
	if (evaluation.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.evaluationDao.findEvaluationTotalCount(PageDTO.create(Evaluation.FIELD_ID, evaluation.getEid())) == 0) {
	throw new BusinessException("修改的商品评价 " + evaluation.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateEvaluation()写法
	}

	private void validateDeleteEvaluation(Long evaluationId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateEvaluation()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
